# coding: utf-8 
# @Time : 2021/5/11 10:11
# @Author : shenshaoxiong
# @FileName: Funcs.py
# @Email   : 765105236@qq.com

from jparser import PageModel
from .FuncTimeout import time_out, timeout_callback
import pymysql
import requests
import hashlib
import time
import re
import sys


# @time_out(2, timeout_callback)
def test1():
    return "ok....."


def get_md5(str_):
    hash = hashlib.md5()
    hash.update(str_.encode('utf-8'))
    return hash.hexdigest()


def get_now_time():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


def get_response(url="", time_out=3):
    result_dict = {}
    try:
        req = requests.get(url=url, timeout=time_out)
        req.encoding = "utf-8"
        state = req.status_code
        html = req.text
        html_len = len(html)
        if html_len > 1024 * 1024 * 3:
            html = html[0: 1024 * 1024 * 3]
        result_dict["url"] = url
        result_dict["response_state"] = state
        result_dict["text"] = html
        result_dict["response_info"] = ""
    except Exception as e:
        request_info = str(e)
        print(request_info)
        result_dict["url"] = url
        result_dict["response_state"] = 0
        result_dict["text"] = ""
        result_dict["response_info"] = request_info

    return result_dict


def insert_mysql(host="", user="", password="", db="", port=3306, table="", field_list=[], values_list=[]):
    sql = "INSERT IGNORE INTO %s(%s) VALUES(%s);" % (table, ",".join(field_list), ("%s," * len(field_list))[0:-1])
    db = pymysql.connect(host=host, user=user, password=password, database=db, port=port, charset="utf8",
                         connect_timeout=300)
    cursor = db.cursor()
    try:
        cursor.executemany(sql, values_list)
        db.commit()
    except Exception as e:
        print(e)
        db.rollback()
    cursor.close()
    db.close()


def get_mysql_data(host="", user="", password="", db="", port=3306, table="", field_list=[], size=None, filter=None,order=None):
    result_list = []
    select_sql = "select %s from %s " % (",".join(field_list), table)
    if filter: select_sql = select_sql + " where " + filter
    if order: select_sql = select_sql + " order by "+ order
    if size: select_sql = select_sql + " limit " + str(size)
    try:
        db = pymysql.connect(host=host, user=user, password=password, database=db, port=port, charset="utf8",
                             connect_timeout=300)
        cursor = pymysql.cursors.SSCursor(db)
        cursor.execute(select_sql)
        while True:
            row = cursor.fetchone()
            if not row:
                break
            a_dict = {}
            for i, k in enumerate(field_list):
                a_dict[k] = row[i]
            result_list.append(a_dict)
        cursor.close()
        db.close()
    except Exception as e:
        print(e)

    return result_list


def update_data(host="", user="", password="", db="", port=3306, sql="", values_list=[]):
    db = pymysql.connect(host=host, user=user, password=password, database=db, port=port, charset="utf8",
                         connect_timeout=300)
    cursor = db.cursor()
    try:
        cursor.executemany(sql, values_list)
        db.commit()
    except Exception as e:
        print(e)
        db.rollback()
    cursor.close()
    db.close()


# @time_out(5, timeout_callback)
def get_html_title_content(html):
    try:
        pm = PageModel(html)
        result = pm.extract()
        title = result['title']
        content = ''
        for x in result['content']:
            if x['type'] == 'text':
                content = '%s%s%s' % (content, x['data'], '\n')
        result = {}.fromkeys(("title", "content"))
        result["title"] = title
        result["content"] = content
        return result
    except Exception as e:
        print(e)
        return {"title": "", "content": ""}


def get_text_date(text=""):
    # print("获取日期:",text);
    text = text.replace("年", "-").replace("月", "-").replace("日", "").replace("/", "-").strip()
    date_list = []
    regex_list = [
        # 2013年8月15日 22:46:21
        "(20\d{2}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})",
        # "2013年8月15日 22:46"
        "(20\d{2}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2})",
        # "2014年5月11日"
        "(20\d{2}-\d{1,2}-\d{1,2})",
        # "2014年5月"
        "(20\d{2}-\d{1,2})",
        # "8月15日"
        "(\d{1,2}-\d{1,2})",
    ]
    for regex in regex_list:
        t = re.search(regex, text)
        if t:
            t = t.group(1)
            date_list.append(t)
    if date_list:
        return max(date_list, key=len).split(" ")[0]
    else:
        return ""

if __name__ == "__main__":
    # print(get_response(url="https://news.sina.com.cn/c/2021-05-13/doc-ikmxzfmm2272222.shtml"))
    print(get_text_date(text=""))
